import { AntDesignTheme } from '@amcax/base';
import { httpApi } from '@app-base/server/httpApi';
import { useDocumentConsumer } from '@app-cad/common/providers/documentProvider';
import {
  Checkbox,
  ConfigProvider,
  Form,
  Input,
  InputRef,
  Modal,
  Select,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';

const { Option } = Select;

interface NewDocModalProps {
  open: boolean;
  onClose: VoidFunction;
}

export const NewDraftingDocModal: React.FC<NewDocModalProps> = ({
  open,
  onClose,
}) => {
  const { documentInfo } = useDocumentConsumer();

  const [loading, setLoading] = useState<boolean>(false);
  const [newWindow, setNewWindow] = useState<boolean>(false);

  const [formValid, setFormValid] = useState<boolean>(false);
  const [form] = Form.useForm();
  const inputRef = useRef<InputRef>(null);

  useEffect(() => {
    if (open && inputRef.current) {
      form.setFieldsValue({ name: '', docType: 'drawing' });

      setTimeout(() => inputRef.current?.focus(), 0);
    }
  }, [form, open]);

  const handleOk = async () => {
    const { name, docType } = await form.validateFields();

    try {
      const { data } = await httpApi.createDocument({
        name,
        type: docType,
        collectionId: documentInfo.collectionId,
      });

      const url = window.location.href;
      const reg = /doc=[^&]*/;
      const newContent = 'doc=' + data.uuid;
      const newUrl = url.replace(reg, newContent);
      const typeReg = /\/collections\/([^/?#]+)/;
      const newType = 'drafting';
      const finalUrl =
        newUrl.replace(typeReg, `/collections/${newType}`) +
        `&fd=${documentInfo.uuid}&fv=${documentInfo.versionDetailResultVo.version}&ft=${documentInfo.type}&fn=${name}`;

      if (window.__MICRO_APP_ENVIRONMENT__ && !newWindow) {
        const globals = (window as any).microApp?.getGlobalData();
        globals?.history?.push(finalUrl.replace(window.location.origin, ''));
      } else {
        window.open(finalUrl, '_blank');
      }
    } finally {
      setLoading(false);
      onClose();
    }
  };

  const handleValuesChange = () => {
    form
      .validateFields()
      .then(() => setFormValid(true))
      .catch(({ errorFields }) => setFormValid(!errorFields?.length));
  };

  return (
    <ConfigProvider theme={AntDesignTheme}>
      <Modal
        open={open}
        closable={!loading}
        width={480}
        title='生成工程图'
        onOk={handleOk}
        okText='确认'
        okButtonProps={{ disabled: !formValid }}
        confirmLoading={loading}
        onCancel={onClose}
        cancelText='取消'
        cancelButtonProps={{ disabled: loading }}
        maskClosable={false}>
        <Form
          form={form}
          disabled={loading}
          name='new_doc_form'
          onValuesChange={handleValuesChange}>
          <Form.Item
            name='name'
            label='文档名称'
            rules={[{ required: true, message: '名称不能为空' }]}>
            <Input
              ref={inputRef}
              onPressEnter={handleOk}
              placeholder='请输入文档名称'
            />
          </Form.Item>
          <Form.Item
            name='docType'
            label='文档类型'
            rules={[{ required: true }]}
            hidden>
            <Select>
              <Option value='drawing'>工程制图</Option>
            </Select>
          </Form.Item>
        </Form>
        <Checkbox
          value={newWindow}
          onChange={(e) => setNewWindow(e.target.checked)}>
          在新窗口中打开
        </Checkbox>
      </Modal>
    </ConfigProvider>
  );
};
